﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.ApplicationBlocks.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace ModuleDuoc
{
    public partial class frmTK_DoanhThu : ModuleDuoc.Base.frmTK_Base
    {
        string loai;
        string _loaiPhieu;
        public frmTK_DoanhThu()
        {
            InitializeComponent();
        }
        public frmTK_DoanhThu(string loaiphieu)
        {
            InitializeComponent();
            _loaiPhieu = loaiphieu;
        }

        private void frmTK_DoanhThu_Load(object sender, EventArgs e)
        {
            this.cboLoaiPhieu.Text = "Tất cả";
            this.dgvDoanhThu.AutoGenerateColumns = false;
            this.dgvDoanhThuCT.AutoGenerateColumns = false;
            loadDoanhThu();
            this.btnExportReport.Enabled = false;
            this.btnExcel.Enabled = false;
        }

        private void loadDoanhThu() // Lấy doanh thu từ bảng phiếu xuất kho
        {
            //string sql = "SELECT sophieu, ngaylap, tongtien, id FROM zD_PHIEUXUATKHO WHERE huy = 0 and ngaylap BETWEEN '" + this.date1.Value.ToString("dd/MM/yyyy HH:mm:ss") + "' AND '" + this.date2.Value.ToString("dd/MM/yyyy HH:mm:ss") + "' ORDER BY ngaylap,sophieu,tongtien,id";
           
            if (this.cboLoaiPhieu.Text == "Tất cả")
            {
                loai = "";
            }
            if (this.cboLoaiPhieu.Text == "Bán lẻ")
            {
                loai = "3";
            }
            else if (this.cboLoaiPhieu.Text == "Nội bộ")
            {
                loai = "4";
            }
            else if (this.cboLoaiPhieu.Text == "Bảo hiểm")
            {
                loai = "5";
            }
            string sql = "SELECT sophieu, ngaylap, tongtien, id FROM zD_PHIEUXUATKHO " +
                        "WHERE loaiphieu like '%"+loai+"%' and huy = 0 and ngaylap BETWEEN '" + this.date1.Value.ToString("MM/dd/yyyy HH:mm:ss") + "' AND '"
                        + this.date2.Value.ToString("MM/dd/yyyy HH:mm:ss") + "' " +
                        "UNION ALL " +
                        "SELECT zdptl.SoHoaDonBanLe, zdptl.NgayLap, -zdptl.TongTien,zdptl.PhieuTraLai_ID " +
                        "FROM zD_PhieuTraLai zdptl " +
                        "WHERE zdptl.DuyetPhieu = 1 AND ngaylap BETWEEN '" + this.date1.Value.ToString("MM/dd/yyyy HH:mm:ss") + "' AND '"
                        + this.date2.Value.ToString("MM/dd/yyyy HH:mm:ss") + "' " +
                        "ORDER BY ngaylap,sophieu,tongtien,id";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            this.dgvDoanhThu.DataSource = dt;
            this.getTongDoanhThu();
            this.loadDoanhThuCT();
        }
        private void getTongDoanhThu()
        {
            Double dt = 0; // Tổng doanh thu
            for (int i = 0; i < this.dgvDoanhThu.Rows.Count; i++)
            {
                dt += Double.Parse(this.dgvDoanhThu.Rows[i].Cells["tongtien"].Value.ToString());
            }
            this.txtTongDoanhThu.Text = "Tổng: " + String.Format("{0:0,0.00 đ}", dt);
        }
        private void loadDoanhThuCT() // Lấy doanh thu từ bảng phiếu xuất kho và xuất kho chi tiết
        {
            try
            {
                string sql = "SELECT mavach, solo, dongia,soluong,thanhtien FROM zD_PHIEUXUATKHOCT WHERE sophieu = '" + this.dgvDoanhThu.Rows[this.dgvDoanhThu.CurrentRow.Index].Cells["sophieu"].Value.ToString() + "'";
                DataTable dt = new DataTable();
                dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                this.dgvDoanhThuCT.DataSource = dt;                
            }
            catch (Exception)
            { }
        }

        public override void btnView_Click(object sender, EventArgs e)
        {
            base.btnView_Click(sender, e);
            loadDoanhThu(); 
        }

        private void dgvDoanhThu_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (float.Parse(this.dgvDoanhThu.Rows[this.dgvDoanhThu.CurrentRow.Index].Cells["TongTien"].Value.ToString()) > 0)
                {
                    this.loadDoanhThuCT();
                }
                else
                {
                    MessageBox.Show("Không xem được phiếu trả lại!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch { }
        }

        private void dgvDoanhThu_KeyDown(object sender, KeyEventArgs e)
        {
            this.loadDoanhThuCT();
        }

        private void dgvDoanhThu_KeyUp(object sender, KeyEventArgs e)
        {
            this.loadDoanhThuCT();
        }
        public override void btnExportReport_Click(object sender, EventArgs e)
        {
            base.btnExportReport_Click(sender, e); ;
            SqlParameter[] parm = new SqlParameter[3];

            parm[0] = new SqlParameter("@tungay", SqlDbType.DateTime, 8);
            parm[0].Value = date1.Value;
            parm[1] = new SqlParameter("@denngay", SqlDbType.DateTime, 8);
            parm[1].Value = date2.Value;
            SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["Main.ConnectionString"],
                CommandType.StoredProcedure,
                "zD_BC_TH_XUATHANG",
                parm);

            string sql = "select mavt,tenvt,sum(soluongban-isnull(tralai,0)) as slban,dongianhap,dongiaban,sum(tongban-isnull(thanhTienTraLai,0)) as tb,ngaylap,(dongiaban-dongianhap)*sum(soluongban-isnull(tralai,0)) as lai";
            sql += " from zD_BC_TongHopBanHang";
            sql += " where soluongban >0 and ngaylap between '" + date1.Value.ToString("MM/dd/yyyy HH:mm:ss") + "' and '" + date2.Value.ToString("MM/dd/yyyy HH:mm:ss") + "'";
            sql += " group by mavt,tenvt,dongianhap,dongiaban,ngaylap";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            frmShowReport frm = new frmShowReport(1);
            frmShowReport._dt = dt;
            frmShowReport.strC = frmShowReport.BC.TKXUATHANG;
            frmShowReport._tungay = date1.Value.ToString("dd/MM/yyyy");
            frmShowReport._denngay = date2.Value.ToString("dd/MM/yyyy");
            float tongtien = 0;
            float tonglai = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                tongtien += float.Parse(dt.Rows[i]["tb"].ToString());
                tonglai += float.Parse(dt.Rows[i]["lai"].ToString());
            }
            frmShowReport._thanhtien = String.Format("{0:0,0}", tongtien);
            frmShowReport._tonglai = String.Format("{0:0,0}", tonglai);
            frm.Show();
        }
    }
}
